package com.base.sdk.util.camera;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import com.base.sdk.util.ToastUtil;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图片选择器 （使用单列的目的是为了试红米手机调用该类不会回收）
 * Created by hp on 2016/10/17.
 */

public class CameraSelectUtil {
    public static final int REQUEST_CODE_CAMERA = 841;
    public static final int REQUEST_CODE_FOR_IMAGE = 842;
    public static final int REQUEST_CODE_FOR_CROP = 3;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    public static final int MEDIA_TYPE_CROP = 3;
    public static final String STORAGE_DIR = "ckd";


    Activity context;
    public File pitcureFile;

    public CameraSelectUtil(Activity context) {
        this.context = context;
    }

    /**
     * 25后调用方法
     */
    public void useCamera() {
        pitcureFile = null;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        pitcureFile = getPictureFile();
        if (pitcureFile == null) {
            return;
        }
        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri fileUri = FileProvider.getUriForFile(context, "com.jtlrm.ckd.provider", pitcureFile);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        context.startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }


    /**
     * 23之前调用方法
     */
    public void selectPic() {
        pitcureFile = null;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        pitcureFile = getPictureFile();
        if (pitcureFile == null) {
            return;
        }
        Uri uri = Uri.fromFile(pitcureFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        context.startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    private File getPictureFile() {
        if (checkSDCard()) {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + STORAGE_DIR + "/" + System.currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            return file;
        } else {
            ToastUtil.TextToast(context, "存储卡不可用");
            return null;

        }
    }

    public void selectPicBoth() {
        String[] data = new String[]{"拍照", "从手机相册中选择"};
        final ActionSheetDialog dialog = new ActionSheetDialog(context, data //
                , null);
        dialog.titleHeight(0).titleTextSize_SP(14.5f)//
                .layoutAnimation(null)//
                .cancelText("取消")
                .show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {

                    switch (position) {
                        case 0:
                            // 调用相机
                            takeCameral();
                            dialog.dismiss();
                            break;
                        case 1:
                            takePicture();
                            dialog.dismiss();
                            break;
                        default:
                            break;
                    }
                    dialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 调用相册
     */
    public void takePicture() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        context.startActivityForResult(intent, REQUEST_CODE_FOR_IMAGE);
    }

    /**
     * 调用相机
     */
    public void takeCameral() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            int check = ContextCompat.checkSelfPermission(context, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= 24) {
                    //调用相机
                    useCamera();
                } else {
                    selectPic();
                }
            } else {
                context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
            selectPic();
        }
    }


    public static boolean checkSDCard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }


}
